package com.xiaou.realm;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.xiaou.entity.Permission;
import com.xiaou.entity.Role;
import com.xiaou.entity.Users;
import com.xiaou.mapper.UserMapper;
import com.xiaou.service.PermissionService;

public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private PermissionService permissionService;
	
	@Override
	public String getName() {
		return "UserRealm";
	}
	/**
	 * 验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		String username = (String) token.getPrincipal();
		Users user = userMapper.findUsersByUsername(username);
		if(null == user) {
			return null;	
			
		}
		Role reRole = permissionService.findRoleByUid(user.getId());
		List<Role> roles = new ArrayList<Role>();
		roles.add(reRole);
		user.setRoleList(roles);
		return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getPassword_salt()),getName());
	}
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("-----------------------------授权------------------------------");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		Users user =  (Users) principals.getPrimaryPrincipal();
		
		Role reRole = permissionService.findRoleByUid(user.getId());
		
		for(Permission permission : reRole.getPermissionList()) {
			authorizationInfo.addStringPermission(permission.getPermission());
		}
		return authorizationInfo;
	}
	
	/**
	 * 清除授权信息
	 */
	@Override
    public  void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("清除授权的缓存");
        /*Cache c = this.getAuthorizationCache();
        Set<Object> keys = c.keys();
        for(Object o:keys) {
            System.out.println("授权缓存:"+o+"-----"+c.get(o)+"----------");
        }*/
        super.clearCachedAuthorizationInfo(principals);
    }

}
	
	

